package com.wnm.util;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DBUtils {
	private static SqlSessionFactory sqlSessionFactory;
	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
	static {
		try {
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("sqlMapConfig.xml"));
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("mybatis加载配置文件失败");
		}
	}

	public static SqlSession getSqlSession() {
		SqlSession sqlSession = threadLocal.get();
		if (sqlSession == null) {
			sqlSession = sqlSessionFactory.openSession();
			threadLocal.set(sqlSession);
		}
		return sqlSession;
	}

	// 关闭连接
	public static void closeSession() {
		SqlSession sqlSession=threadLocal.get();
		if (sqlSession != null) {
			sqlSession.close();
			threadLocal.remove();// 从ThreadLocal移除
		}
	}

}
